<?php

/**
 * @Author: feidao@ibantang.com, 2019, all rights reserved
 * @Date: 2019-06-03
 * @Time: 16:12
 * @Brief:
 */

namespace Core\Common\Base\Db;

trait Reconnect
{
    /**
     * 重连
     */
    protected function reconnect()
    {
        // 尝试用当前配置连接2次
        $this->link = null;
        $this->connect(2);
        if ($this->link) {
            return;
        }

        // 如果当前处于事物或prepare，则不能切换连接
        if ($this->inTrans || $this->inPrepare) {
            return;
        }

        // 标记本次连接失败
        Connection::flagReconnectError($this->host, $this->port, $this->db, $this->user);
        $bakHosts = $this->bakHosts;
        if (empty($bakHosts)) {
            return;
        }

        // 从备用host里获取连接
        $srcHost = $this->host;
        foreach ($bakHosts as $tmpHost) {
            if ($srcHost == $tmpHost) {
                continue;
            }
            $srcHost = $this->host;
            $this->host = $tmpHost;
            $connRet = $this->connect(1);
            if ($this->link && 0 === $connRet) {
                $this->host = $srcHost;
                Connection::reConnectionSuccess($tmpHost, $this->port, $srcHost, $this->port, $this, $this->db, $this->user);
                break;
            } else {
                Connection::flagReconnectError($tmpHost, $this->port, $this->db, $this->user);
            }
        }
    }
}
